﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel;
using IdentityModel.Client;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using WebApi.Common;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class IdentityController : ControllerBase
    {
        private const string Secret = "db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw==";

        [HttpGet]
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="key">JwtKey</param>
        /// <returns></returns>
        public string GenerateToken(string userId)
        {
            //var tokenHandler = new JwtSecurityTokenHandler();
            //var keyBytes = Convert.FromBase64String(Secret);  // 生成二进制字节数组;
            //var authTime = DateTime.UtcNow;
            //var expireaAt = authTime.AddHours(24);//token过期时间
            //var timestamp = TimeStamp.GenerateTimeStamp(authTime);//生成日间戳
            //var sign = MyUnity.GetMd5Upper32((userId + "&" + timestamp ).ToUpper());
            //var tokenDescriptor = new SecurityTokenDescriptor()
            //{
            //    Subject = new ClaimsIdentity(new Claim[] {
            //     new Claim(JwtClaimTypes.Audience,"webApiapi"),
            //     new Claim(JwtClaimTypes.Issuer,"hengfeng"),
            //     new Claim(JwtClaimTypes.Id,userId),
            //     new Claim("timestamp",timestamp),
            //     new Claim("sign",sign),
            //       }),
            //    Expires = expireaAt,
            //    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyBytes),
            //    SecurityAlgorithms.HmacSha256Signature)
            //};
            //var token = tokenHandler.CreateToken(tokenDescriptor);
            //var tokenString = tokenHandler.WriteToken(token);
            var idsUrl = "http://localhost:5000";
            var discoverClient = new DiscoveryClient(idsUrl) { Policy = { RequireHttps = false} };
            var disco = discoverClient.GetAsync().Result;

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return "";
            }
            var tokenClient = new TokenClient(disco.TokenEndpoint, "webApiapi", "webApiapi");
            var tokenResponse = tokenClient.RequestClientCredentialsAsync("webAp2").Result;
            
            return tokenResponse.AccessToken;
        }

        [HttpPost("principal")]
        public  ClaimsPrincipal GetPrincipal([FromBody]string token)
        { // 此方法用解码字符串token，并返回秘钥的信息对象
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler(); // 创建一个JwtSecurityTokenHandler类，用来后续操作
                var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken; // 将字符串token解码成token对象
                if (jwtToken == null)
                    return null;
                var symmetricKey = Convert.FromBase64String(Secret); // 生成编码对应的字节数组
                var validationParameters = new TokenValidationParameters() // 生成验证token的参数
                {
                    RequireExpirationTime = true, // token是否包含有效期
                    ValidateIssuer = false, // 验证秘钥发行人，如果要验证在这里指定发行人字符串即可
                    ValidateAudience = false, // 验证秘钥的接受人，如果要验证在这里提供接收人字符串即可
                    IssuerSigningKey = new SymmetricSecurityKey(symmetricKey) // 生成token时的安全秘钥
                };
                SecurityToken securityToken; // 接受解码后的token对象
                var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
                return principal; // 返回秘钥的主体对象，包含秘钥的所有相关信息
            }

            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
